package com.xuyiwei.xblog.controller;

import com.xuyiwei.xblog.constant.XConstant;
import com.xuyiwei.xblog.service.ISysUserService;
import com.xuyiwei.xblog.utils.CaptchaUtil;
import com.xuyiwei.xblog.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by xuyiwei on 2019/7/30.
 */
@Api(value = "主业模块")
@RestController
public class IndexController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     *
     * @param response
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/captcha.jpg")
    public Result<Map> captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 生成图片验证码
        BufferedImage image = CaptchaUtil.createImage();
        // 生成文字验证码
        String randomText = CaptchaUtil.drawRandomText(image);
        // 保存到验证码到 redis 有效期两分钟
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(XConstant.X_IMAGE_SESSION_KEY+"_"+uuid, randomText.toLowerCase(),
                2, TimeUnit.MINUTES);

        // 生成图片验证码
        ByteArrayOutputStream outputStream =  new ByteArrayOutputStream();

        ImageIO.write(image, "jpeg", outputStream);
        // 生成captcha的token
        Map<String, Object> map = new HashMap();
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        map.put("img", encoder.encode(outputStream.toByteArray()));
        map.put("uuid",  uuid);
        return Result.ok(map);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/login")
    public Result<String> login(String username, String password, String captcha,String uuid, HttpServletRequest request) {
        return Result.ok(userService.login(username, password, captcha,uuid, request));
    }



}
